<?php

namespace app\common\service;

use think\Response;

trait ResponseService
{
    use SingletonService;

    /**
     * 返回成功
     * @param string $message
     * @param string $status
     * @param array $data
     * @return Response
     */
    public function responseSuccess($message = '操作成功', $data = [], $status = '1')
    {
        $response['status'] = $status;
        $response['msg'] = $message;
        $response['data'] = $data;
        return $this->response($response);
    }


    /**
     * 返回失败
     * @param string $message
     * @param string $status
     * @param array $data
     * @return Response
     */
    public function responseError($message = '网络错误', $data = [], $status = '0')
    {
        $response['status'] = $status;
        $response['msg'] = $message;
        $response['data'] = $data;
        return $this->response($response);
    }


    /**
     * 中断回复
     * @param string $message
     */
    public function responseException($message = '网络错误')
    {
        if (!is_array($message)) {
            $response = $this->responseError($message);
            throw new \think\exception\HttpResponseException($response);
        } else {
            $this->httpException($message);
        }
    }

    /**
     * 中断回复
     * @param array $message
     * @param int $code
     * @param array $header
     */
    public function httpException(array $message = [], int $code = 200, array $header = [])
    {
        $response = $this->response($message, $code, $header);
        throw new \think\exception\HttpResponseException($response);
    }


    /**
     * 响应格式
     * @param array $message
     * @param int $code
     * @param array $header
     * @return Response
     */
    protected function response($message = [], $code = 200, $header = [])
    {
        return Response::create($message, 'json', $code)->header($header);
    }


}